import axios from 'axios';
import wmx from '@/common/wmx';
import { ElMessage, ElLoading } from 'element-plus';
import api from '@/api/api';
import qs from 'qs';
export default {
    //加载
    install(app) {
        let instance = this.init();
        app.config.globalProperties.$get = instance.requestGet;
        app.config.globalProperties.$post = instance.requestPost;
        app.config.globalProperties.$token = localStorage.getItem('token');
    },
    // 初始化
    init() {
        //代理实例
        let proxy = wmx.app.config.globalProperties;
        axios.defaults.baseURL = proxy.$api
        axios.defaults.timeout = 1000*60*60*24*10
        
        let loading = null
        let set_loading = false

        //请求拦截器
        axios.interceptors.request.use((config) => {
            let token = localStorage.getItem('token');
            token && (config.headers['token'] = token);
            return config;
        });
        //响应拦截器
        axios.interceptors.response.use(
            (response) => {
                if (set_loading && loading) {
                    loading && loading.close()
                }
                // 登录失败，没有权限，登录过期
                if (response.data.code === 202) {
                    localStorage.removeItem('token');
                    proxy.$router.replace('/')
                    
                }
                // 返回响应信息
                if (response.data.code != 0) {
                    ElMessage({
                        type: 'error',
                        message: response.data.message,
                    });
                }
                return response.data;
            },
            (error) => {
                loading && loading.close()
                let message = "服务器开小差了……";
                if (error.message === "Network Error") {
                    message = "网络异常……";
                } else if (error.message.indexOf("timeout") > -1) {
                    message = "请求超时……";
                }
                ElMessage({
                    type: 'error',
                    message: message
                });
                return Promise.reject(error);
            }
        );

        const requestGet = async (name, data, is_loading = true, set_type = false) => {
            set_loading = is_loading
            if (is_loading) {
                loading = ElLoading.service({
                    lock: true,
                    text: 'Loading',
                    background: 'rgba(0, 0, 0, 0.2)',
                })
            }
            // data['token'] = get_token();
            let conf = {
                method: "GET",
                url: api[name],
                params: data,
            };
            if (set_type) {
                conf.transformRequest= [
                    function(data) {
                      const formData = new FormData()
                      for (var key in data) {
                        if (!data[key]) {
                            data[key] = ''
                        }
                        formData.append(String(key), data[key])
                      }
                      return formData
                    }
                  ]
            }
            
            let res = await axios(conf);
            if (is_loading && loading) {
                loading && loading.close()
            }
            return res
        }

        const requestPost = async (name, data, is_loading= true, set_type=false)=> {
            set_loading = is_loading
            if (is_loading) {
                loading = ElLoading.service({
                    lock: true,
                    text: 'Loading',
                    background: 'rgba(0, 0, 0, 0.4)',
                })
            } 
        
            let conf = {
                method: "POST",
                url: api[name],
            }
        
            if (set_type) {
                conf['data'] = data
                conf.transformRequest= [
                    function(data) {
                      const formData = new FormData()
                      for (var key in data) {
                        if (!data[key]) {
                            data[key] = ''
                        }
                        formData.append(String(key), data[key])
                      }
                      return formData
                    }
                  ]
            } else {
               conf['data'] = qs.stringify(data)
            }
            let res = await axios(conf);
            if (is_loading && loading) {
                loading && loading.close()
            }
            
            return res
        }
        
        
        //返回实例
        return {
            requestGet,
            requestPost
        };
    }
};
